package com.hxzy.controller;

import com.hxzy.common.domain.AjaxResult;
import com.hxzy.common.utils.ServletUtils;
import com.hxzy.dto.AdminLoginDTO;
import com.hxzy.entity.AdminUser;
import com.hxzy.service.AdminUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * 类说明
 *
 * @author admin
 * @date 2021-09-01
 */
@Controller
@RequestMapping(value = "/admin")
public class LoginController {

    @Autowired
    private AdminUserService  adminUserService;

    /**
     * 显示登录界面
     * @param request
     * @param response
     * @param model
     * @return
     */
    @GetMapping(value = "/login")
    public String  login(HttpServletRequest request, HttpServletResponse response, Model  model){

       // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }

        //开放注册（显示注册按钮）
        model.addAttribute("isAllowRegister",true);
        //显示记住我
        model.addAttribute("isRemembered",false);

        //开启验证码
        model.addAttribute("captchaEnabled",true);

        //viewName
        return "login";
    }


    @ResponseBody
    @PostMapping(value = "/login")
    public AjaxResult loginValidate( AdminLoginDTO adminLoginDTO, HttpSession session){
       //session过期
       if(session.getAttribute("captchaValue")==null){
           return AjaxResult.warn("验证码已过期，请刷新后再试!");
       }

       //判断用户输入的验证码 与  系统生成的验证码是否一致
        String sysCode=session.getAttribute("captchaValue").toString();
        if(!sysCode.equalsIgnoreCase(adminLoginDTO.getValidateCode())){
            return AjaxResult.warn("验证码错误!");
        }

        //加上shiro框架
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(adminLoginDTO.getUsername(), adminLoginDTO.getPassword());
        //创建一个登录Subject
        Subject  subject= SecurityUtils.getSubject();
        AdminUser  adminUser=null;
        //3、登录，自动调用你写的 realm类
        try {
            subject.login(usernamePasswordToken);

            adminUser= (AdminUser) subject.getPrincipal();

        }catch(UnknownAccountException e1){
            return AjaxResult.warn("用户名或密码错误！");
        } catch(IncorrectCredentialsException e2 ){
            return AjaxResult.warn("用户名或密码错误！");
        }catch(LockedAccountException e3){
            return AjaxResult.warn("账户被锁定不允许登录！");
        }

        return AjaxResult.success();

    }


}
